package huoye.shops.huoye.user.activity;

import android.Manifest;
import android.content.Context;
import android.content.res.AssetManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import com.codeideology.android.utils.AssetUtils;
import com.codeideology.android.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import huoye.shops.R;
import huoye.shops.base.APIUrls;
import huoye.shops.base.BaseActivity;
import huoye.shops.base.UserManager;
import huoye.shops.huoye.user.model.AreaInfo;
import huoye.shops.huoye.user.model.Province;
import huoye.shops.huoye.user.model.SelectCityData;
import huoye.shops.huoye.user.presenter.SelectCityPresenter;
import huoye.shops.huoye.user.view.ISelectCityView;
import pub.devrel.easypermissions.EasyPermissions;

public class SelectNewActivity extends BaseActivity implements ISelectCityView, EasyPermissions.PermissionCallbacks {

    @BindView(R.id.sp_province)
    Spinner spProvince;
    @BindView(R.id.sp_city)
    Spinner  spCity;
    @BindView(R.id.sp_area)
    Spinner  spArea;
    @BindView(R.id.tv_select_city)
    TextView tvSelectCity;



    private SelectCityPresenter mSelectCityPresenter;

    @OnClick(R.id.btn_ok)
    void onOkClick(){
        if(provinceName.equals("-请选择-") || cityName.equals("-请选择-")||areaName.equals("-请选择-")){
            makeToast("请选择区域");
            return;
        }
        mSelectCityPresenter.selectCity(provinceName,cityName,areaName);
    }

    private ArrayAdapter<String> provinceAdapter;
    private ArrayAdapter<String> cityAdapter;
    private ArrayAdapter<String> areaAdapter;


    private List<String> provinceList = new ArrayList<>(); // 所有省份的list
    private List<String> cityList = new ArrayList<>();     // 当前选中省份的城市
    private List<String> areaList = new ArrayList<>();     // 当前选中城市的城区

    private String provinceName;    // 省的名字
    private String cityName;        // 市的名字
    private String areaName;        // 区的名字


    @Override
    protected int getContentViewId() {
        return R.layout.activity_select_city;
    }

    @Override
    protected void initView(@Nullable Bundle bundle) {

        mSelectCityPresenter = new SelectCityPresenter();
        mSelectCityPresenter.addTaskListener(this);
        mSelectCityPresenter.onStart();


        showProvinceData();
        showCityData();
        showAreaData();
        openPower();
        if(StringUtils.isNotEmpty(UserManager.getInstance().getProvince())){
            getUserSite();
        }else {
            mSelectCityPresenter.getAreaInfo(ftype,"");
        }

    }

    private void getUserSite(){
        isCityNull = true;
        provinceList.add(UserManager.getInstance().getProvince());
        cityList.add(UserManager.getInstance().getCity());
        areaList.add(UserManager.getInstance().getArea());
        provinceAdapter.notifyDataSetChanged();
        cityAdapter.notifyDataSetChanged();
        areaAdapter.notifyDataSetChanged();
        mSelectCityPresenter.getAreaInfo(ftype,"");

    }

    private boolean isCityNull;

    private String ftype = "0";


    public static List<String> removeDuplicate(List<String> list) {
        Set set = new LinkedHashSet<String>();
        set.addAll(list);
        list.clear();
        list.addAll(set);
        return list;
    }


    @Override
    public void getAreaData(List<AreaInfo> list) {
        switch (ftype){
            case "0":
                provinceList.clear();
                provinceList.add("-请选择-");
                for (int i = 0 ; i < list.size();i++){
                    provinceList.add(list.get(i).getSname());
                }
                if(!isCityNull){
                    provinceAdapter.notifyDataSetChanged();
                }

                break;
            case "1":
                cityList.clear();
                cityList.add("-请选择-");
                for (int i = 0 ; i < list.size();i++){
                    cityList.add(list.get(i).getSname());
                }
                // 刷新城市列表
                cityAdapter.notifyDataSetChanged();
            case "2":
                areaList.clear();
                areaList.add("-请选择-");
                for (int i = 0 ; i < list.size();i++){
                    areaList.add(list.get(i).getSname());
                }
                // 刷新城市列表
                areaAdapter.notifyDataSetChanged();
                break;
        }
    }


    private void setCityDefaultString(){
        cityList.clear();
        cityList.add("-请选择-");
        cityName = "-请选择-";
        cityAdapter.notifyDataSetChanged();
    }

    private void setAreaDefaultString(){
        areaList.clear();
        areaList.add("-请选择-");
        areaName = "-请选择-";
        areaAdapter.notifyDataSetChanged();
    }



    /**
     * 展示数据
     */
    private void  showProvinceData() {
        // 显示省份数据

        removeDuplicate(provinceList);
        spProvince.setAdapter(provinceAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, provinceList));
        spProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(isCityNull){
                    provinceName = UserManager.getInstance().getProvince();
                }else {
                    provinceName = provinceList.get(position);
                    // 获取当前省份对应的城市list
                    Log.e("test","a"+provinceName);
                    if(!provinceName.equals("-请选择-")){
                        ftype = "1";
                        mSelectCityPresenter.getAreaInfo("1",provinceName);
                    }
                    setCityDefaultString();
                    setAreaDefaultString();
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });



    }


    private void showCityData(){
        // 显示城市数据
        spCity.setAdapter(cityAdapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item, cityList));
        spCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                if(isCityNull){
                    cityName = UserManager.getInstance().getCity();
                }else {
                    cityName = cityList.get(position);
                    Log.e("test","b"+cityName);
                    if(!cityName.equals("-请选择-")){
                        ftype = "2";
                        mSelectCityPresenter.getAreaInfo("2",cityName);
                    }

                    setAreaDefaultString();
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void showAreaData(){
        // 显示城区数据
        spArea.setAdapter(areaAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, areaList));
        spArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(isCityNull){
                    areaName = UserManager.getInstance().getArea();
                    isCityNull = false;
                }else {
                    areaName = areaList.get(position);
                }


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }



    @Override
    public void getUrl(SelectCityData selectCityData) {
      /*  tvSelectCity.setText((provinceName.equals(cityName) ? "" : provinceName+" ") + cityName +" "+ areaName);
        String s = tvSelectCity.getText().toString();*/



        UserManager.getInstance().saveProvince(provinceName);
        UserManager.getInstance().saveCity(cityName);
        UserManager.getInstance().saveArea(areaName);

        UserManager.getInstance().saveUrl(selectCityData.getApiUrl());
        UserManager.getInstance().saveImageUrl(selectCityData.getOssUrl());
        startActivity(LoginActivity.class);
    }






    //打开定位和存储权限
    private void openPower(){
        String[] perms = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {

            // 已经申请过权限，做想做的事
        } else {
            // 没有申请过权限，现在去申请
            EasyPermissions.requestPermissions(this, "打开定位,相机，存储权限",

                    APIUrls.COMMON_CONFIG.PERMISSIONS_CODE, perms);
        }

    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        //无权限，且被选择"不再提醒"：提醒客户到APP应用设置中打开权限

        if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            makeToast("拒绝权限，不再弹出询问框，请前往APP应用设置中打开此权限");
        } else {//无权限，只是单纯被拒绝
            makeToast( "拒绝权限，等待下次询问哦");
        }
    }
}
